<template>
  <div class="admin-applications">
    <div class="container">
      <h1 class="page-title">领养申请管理</h1>
      
      <div class="admin-actions">
        <div class="left-actions">
          <el-button type="primary" @click="loadApplications" :loading="loading">
            <i class="el-icon-refresh"></i> 刷新数据
          </el-button>
        </div>
        <div class="right-actions">
          <el-input
            placeholder="搜索申请..."
            v-model="searchQuery"
            class="search-input"
            prefix-icon="el-icon-search"
            clearable
          />
          
          <el-select v-model="statusFilter" placeholder="状态过滤" class="status-filter" @change="handleStatusChange">
            <el-option label="全部状态" value="" />
            <el-option label="待审核" value="pending" />
            <el-option label="已通过" value="approved" />
            <el-option label="已拒绝" value="rejected" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </div>
      </div>
      
      <el-card class="applications-table-card" v-loading="loading">
        <!-- 申请列表 -->
        <template v-if="filteredApplications.length > 0">
          <el-table
            :data="filteredApplications"
            style="width: 100%"
            border
            stripe
            :default-sort="{ prop: 'created_at', order: 'descending' }"
          >
            <el-table-column prop="id" label="ID" width="80" sortable />
            
            <el-table-column prop="name" label="申请人" width="120">
              <template #default="scope">
                <el-tooltip :content="`邮箱: ${scope.row.email || '未提供'}\n电话: ${scope.row.phone || '未提供'}`" placement="top" effect="light">
                  <span>{{ scope.row.name || '未知' }}</span>
                </el-tooltip>
              </template>
            </el-table-column>
            
            <el-table-column label="宠物名称" width="180">
              <template #default="scope">
                <div class="pet-info">
                  <el-image 
                    :src="getPetImageUrl(scope.row.pet)" 
                    fit="cover"
                    class="pet-thumbnail"
                  >
                    <template #error>
                      <div class="image-placeholder">
                        <i class="el-icon-picture-outline"></i>
                      </div>
                    </template>
                  </el-image>
                  <el-tooltip 
                    :content="scope.row.pet ? 
                      `品种: ${scope.row.pet.breed || '未知'}\n年龄: ${scope.row.pet.age ? scope.row.pet.age + '岁' : '未知'}\n性别: ${formatGender(scope.row.pet.gender)}` : 
                      '暂无详细信息'" 
                    placement="top" 
                    effect="light"
                  >
                    <span class="pet-name">{{ scope.row.pet ? scope.row.pet.name : '未知' }}</span>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
            
            <el-table-column prop="phone" label="联系电话" width="130">
              <template #default="scope">
                <span v-if="scope.row.phone">{{ scope.row.phone }}</span>
                <span v-else class="no-data">未提供</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="created_at" label="申请时间" width="180" sortable>
              <template #default="scope">
                {{ formatDate(scope.row.created_at || scope.row.application_date) }}
              </template>
            </el-table-column>
            
            <el-table-column prop="status" label="状态" width="100" sortable>
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status || (scope.row.pet && scope.row.pet.is_adopted))">
                  {{ formatStatus(scope.row.status || (scope.row.pet && scope.row.pet.is_adopted)) }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column label="原因" show-overflow-tooltip>
              <template #default="scope">
                {{ scope.row.reason_for_adoption || '无' }}
              </template>
            </el-table-column>
            
            <el-table-column label="操作" width="130" fixed="right">
              <template #default="scope">
                <el-dropdown trigger="hover" @command="(command) => handleCommand(command, scope.row)" placement="bottom">
                  <el-button size="small" type="primary" plain class="action-button">
                    操作<i class="el-icon-arrow-down el-icon--right"></i>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="view" icon="el-icon-view">查看详情</el-dropdown-item>
                      <template v-if="isStatusPending(scope.row)">
                        <el-dropdown-item command="approve" icon="el-icon-check" class="approve-action">通过</el-dropdown-item>
                        <el-dropdown-item command="reject" icon="el-icon-close" class="reject-action">拒绝</el-dropdown-item>
                      </template>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="pagination-container">
            <el-pagination
              background
              layout="prev, pager, next"
              :total="totalApplications"
              :page-size="pageSize"
              :current-page="currentPage"
              @current-change="handlePageChange"
            />
          </div>
        </template>
        
        <el-empty 
          v-else 
          description="没有找到申请数据" 
          :image-size="200"
        >
          <template #description>
            <p>没有找到任何申请数据</p>
            <p class="error-hint" v-if="loadError">错误信息: {{ loadError }}</p>
          </template>
          <el-button type="primary" @click="loadApplications">重新加载</el-button>
        </el-empty>
      </el-card>
    </div>
    
    <!-- 申请详情对话框 -->
    <el-dialog
      title="申请详情"
      v-model="detailDialogVisible"
      width="80%"
      :destroy-on-close="true"
      class="application-detail-dialog"
    >
      <div v-if="loadingDetail" class="loading-container">
        <el-skeleton :rows="10" animated />
      </div>
      
      <div v-else-if="currentApplication" class="application-detail">
        <el-row :gutter="20">
          <!-- 左侧信息 -->
          <el-col :span="16">
            <!-- 基本信息 -->
            <div class="detail-card">
              <h3>基本信息</h3>
              <el-descriptions :column="2" border>
                <el-descriptions-item label="申请ID">{{ currentApplication.id }}</el-descriptions-item>
                <el-descriptions-item label="申请状态">
                  <el-tag :type="getStatusType(currentApplication.status)">
                    {{ formatStatus(currentApplication.status) }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="申请人">{{ currentApplication.name || (currentUser && currentUser.name) || '未知' }}</el-descriptions-item>
                <el-descriptions-item label="联系电话">{{ currentApplication.phone || (currentUser && currentUser.phone) || '未提供' }}</el-descriptions-item>
                <el-descriptions-item label="电子邮箱">{{ currentApplication.email || (currentUser && currentUser.email) || '未提供' }}</el-descriptions-item>
                <el-descriptions-item label="申请时间">{{ formatDate(currentApplication.created_at || currentApplication.application_date) }}</el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- 申请原因 -->
            <div class="detail-card">
              <h3>申请原因</h3>
              <div class="content-box">
                {{ currentApplication.reason_for_adoption || '未填写' }}
              </div>
            </div>

            <!-- 生活环境 -->
            <div class="detail-card">
              <h3>生活环境描述</h3>
              <div class="content-box">
                {{ currentApplication.living_situation || currentApplication.living_environment || '未填写' }}
              </div>
            </div>

            <!-- 养宠经验 -->
            <div class="detail-card">
              <h3>养宠经验</h3>
              <div class="content-box">
                {{ currentApplication.previous_pet_experience || '未填写' }}
              </div>
            </div>
          </el-col>

          <!-- 右侧信息 -->
          <el-col :span="8">
            <!-- 宠物信息卡片 -->
            <div class="detail-card pet-card">
              <h3>宠物信息</h3>
              <div v-if="currentPet" class="pet-info-container">
                <div class="pet-image-wrapper">
                  <el-image 
                    :src="getPetImageUrl(currentPet)" 
                    fit="cover"
                    class="pet-image"
                  >
                    <template #error>
                      <div class="image-placeholder">
                        <i class="el-icon-picture-outline"></i>
                        <span>暂无图片</span>
                      </div>
                    </template>
                  </el-image>
                </div>
                <div class="pet-details">
                  <div class="pet-name">{{ currentPet.name || '未知' }}</div>
                  <div class="pet-meta">
                    <span>{{ currentPet.category ? currentPet.category.name : (getCategoryName(currentPet.category_id) || '未知') }}</span>
                    <span>{{ formatGender(currentPet.gender) }}</span>
                    <span>{{ currentPet.age ? `${currentPet.age}岁` : '年龄未知' }}</span>
                  </div>
                  <el-tag :type="currentPet.status === 'available' ? 'success' : 'info'" class="pet-status">
                    {{ currentPet.status === 'available' ? '可领养' : '已领养' }}
                  </el-tag>
                  <el-button type="primary" size="small" class="view-pet-btn" @click="$router.push(`/pets/${currentPet.id}`)">
                    查看宠物详情
                  </el-button>
                </div>
              </div>
              <el-empty v-else description="暂无宠物信息" />
            </div>

            <!-- 处理申请区域 -->
            <div v-if="isStatusPending(currentApplication)" class="detail-card action-card">
              <h3>处理申请</h3>
              <el-form :model="processForm" label-width="100px">
                <el-form-item label="管理员备注">
                  <el-input 
                    type="textarea" 
                    v-model="processForm.admin_comments" 
                    :rows="3" 
                    placeholder="请输入备注信息（可选）"
                  />
                </el-form-item>
                
                <el-form-item class="action-buttons">
                  <el-button 
                    type="success" 
                    @click="approveApplicationWithComment"
                    :loading="processing"
                  >
                    通过申请
                  </el-button>
                  
                  <el-button 
                    type="danger" 
                    @click="rejectApplicationWithComment"
                    :loading="processing"
                  >
                    拒绝申请
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
            
            <div v-else class="detail-card">
              <h3>管理员备注</h3>
              <div class="content-box">
                {{ currentApplication.admin_comments || '无备注' }}
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useStore } from 'vuex';
import axios from 'axios';

export default {
  name: 'AdminApplications',
  setup() {
    const store = useStore();
    const router = useRouter();
    const route = useRoute();
    const API_URL = '/api';
    
    // 状态
    const loading = ref(true);
    const applications = ref([]);
    const searchQuery = ref('');
    const statusFilter = ref('');
    const currentPage = ref(1);
    const pageSize = ref(10);
    const detailDialogVisible = ref(false);
    const currentApplication = ref(null);
    const processing = ref(false);
    const loadError = ref(null);
    const currentPet = ref(null);
    const currentUser = ref(null);
    const loadingDetail = ref(false);
    
    // 计算各种状态的申请数量
    const pendingApplicationsCount = computed(() => {
      return applications.value.filter(app => app.status === 'pending').length;
    });
    
    const approvedApplicationsCount = computed(() => {
      return applications.value.filter(app => app.status === 'approved').length;
    });
    
    const rejectedApplicationsCount = computed(() => {
      return applications.value.filter(app => app.status === 'rejected').length;
    });
    
    // 获取申请统计数据，用于仪表盘
    const getApplicationStats = () => {
      return {
        pendingApplications: pendingApplicationsCount.value,
        successfulAdoptions: approvedApplicationsCount.value,
        recentApplications: applications.value.slice(0, 5).map(app => ({
          id: app.id,
          user_name: app.name,
          pet_name: app.pet ? app.pet.name : '未知',
          created_at: app.created_at,
          status: app.status
        })),
        pendingTasks: applications.value
          .filter(app => app.status === 'pending')
          .slice(0, 3)
          .map(app => ({
            id: app.id,
            category: 'application',
            text: `${app.name}的领养申请`,
            tag: '待审核',
            tagType: 'warning',
            link: `/admin/applications?id=${app.id}`
          }))
      };
    };
    
    // 处理表单
    const processForm = ref({
      admin_comments: ''
    });
    
    // 获取认证头
    const authHeader = computed(() => {
      const token = store.getters['auth/token'];
      return {
        headers: {
          'Authorization': `Bearer ${token}`,
          'x-auth-token': token
        }
      };
    });
    
    // 根据筛选条件过滤申请
    const filteredApplications = computed(() => {
      let result = applications.value;
      
      // 按状态过滤
      if (statusFilter.value) {
        result = result.filter(app => app.status === statusFilter.value);
      }
      
      // 按搜索词过滤
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase();
        result = result.filter(app => 
          (app.name && app.name.toLowerCase().includes(query)) ||
          (app.email && app.email.toLowerCase().includes(query)) ||
          (app.phone && app.phone.includes(query)) ||
          (app.pet && app.pet.name && app.pet.name.toLowerCase().includes(query))
        );
      }
      
      return result;
    });
    
    const totalApplications = computed(() => filteredApplications.value.length);
    
    // 加载所有申请
    const loadApplications = async () => {
      loading.value = true;
      loadError.value = null;
      
      try {
        const token = store.getters['auth/token'];
        if (!token) {
          throw new Error('未登录或认证令牌已过期，请重新登录');
        }
        
        const headers = {
          'Authorization': `Bearer ${token}`,
          'x-auth-token': token
        };
        
        console.log('正在获取申请数据');
        
        // 发送请求获取申请列表
        const response = await axios.get(
          `/api/adoptions/applications${statusFilter.value ? `?status=${statusFilter.value}` : ''}`,
          { headers }
        );
        
        // 处理响应数据
        let applicationsList = [];
        
        if (response.data && response.data.applications) {
          applicationsList = response.data.applications;
          
          // 更新分页信息
          currentPage.value = response.data.pagination?.page || 1;
          pageSize.value = response.data.pagination?.limit || 10;
        }
        
        // 记录数量但不记录用户ID
        console.log('获取到的申请数据条数:', applicationsList.length);
        
        // 处理每条申请数据
        const processedApplications = await Promise.all(
          applicationsList.map(async (app, index) => {
            // 处理日期
            let applicationDate = app.application_date || app.created_at || new Date().toISOString();
            
            // 申请人信息
            let applicantName = app.applicant_name || app.name || '未知';
            let applicantPhone = app.applicant_phone || app.phone || '未知';
            let applicantEmail = app.applicant_email || app.email || '未知';
            
            // 如果申请中没有完整的用户信息，尝试获取
            if (app.user_id && (!app.applicant_name || !app.email)) {
              // 尝试获取用户信息
              try {
                const userResponse = await axios.get(`${API_URL}/users/${app.user_id}`, { headers });
                
                if (userResponse.data) {
                  const userData = userResponse.data;
                  applicantName = userData.full_name || userData.username || applicantName;
                  applicantPhone = userData.phone || applicantPhone;
                  applicantEmail = userData.email || applicantEmail;
                }
              } catch (userError) {
                // 尝试另一个API端点
                try {
                  const userResponse = await axios.get(`${API_URL}/users?id=${app.user_id}`, { headers });
                  
                  if (userResponse.data && userResponse.data.length > 0) {
                    const userData = userResponse.data[0];
                    applicantName = userData.full_name || userData.username || applicantName;
                    applicantPhone = userData.phone || applicantPhone;
                    applicantEmail = userData.email || applicantEmail;
                  }
                } catch (secondUserError) {
                  // 尝试从本地用户列表中查找
                  try {
                    const userData = store.getters['users/allUsers'].find(u => u.id === app.user_id);
                    
                    if (userData) {
                      applicantName = userData.full_name || userData.username || applicantName;
                      applicantPhone = userData.phone || applicantPhone;
                      applicantEmail = userData.email || applicantEmail;
                    }
                  } catch (localUserError) {
                    console.error('获取用户信息失败');
                  }
                }
              }
            } else if (!app.user_id) {
              console.log('申请缺少用户ID信息');
            }
            
            // 宠物信息获取
            let petInfo = app.pet || null;
            
            if (app.pet_id) {
              try {
                const petResponse = await axios.get(`${API_URL}/pets/${app.pet_id}`, { headers });
                
                if (petResponse.data) {
                  petInfo = petResponse.data;
                }
              } catch (petError) {
                console.error('获取宠物信息失败');
              }
            } else {
              console.log('申请缺少宠物ID信息');
            }
            
            const processedApp = {
              id: app.id,
              user_id: app.user_id,
              pet_id: app.pet_id,
              pet: petInfo,
              name: applicantName,
              phone: applicantPhone,
              email: applicantEmail,
              status: app.status || 'pending',
              created_at: applicationDate || app.created_at,
              application_date: app.application_date,
              approval_date: app.approval_date,
              reason_for_adoption: app.reason_for_adoption || app.adoption_reason || '',
              living_situation: app.living_situation || app.living_environment || '',
              previous_pet_experience: app.previous_pet_experience || ''
            };
            
            return processedApp;
          })
        );
        
        applications.value = processedApplications;
        
        // 如果URL中有申请ID，自动打开详情
        const applicationId = route.query.id;
        if (applicationId) {
          const application = applications.value.find(app => app.id === parseInt(applicationId));
          if (application) {
            viewApplication(application);
          }
        }
        
      } catch (error) {
        console.error('获取申请列表失败');
        loadError.value = error.response?.data?.message || error.message || '未知错误';
        ElMessage.error('获取申请列表失败: ' + loadError.value);
        applications.value = [];
      } finally {
        loading.value = false;
      }
    };
    
    // 查看申请详情
    const viewApplication = async (application) => {
      console.log('获取申请详情');
      
      detailDialogVisible.value = true;
      currentApplication.value = { ...application };
      loadingDetail.value = true;
      
      try {
        const token = store.getters['auth/token'];
        const headers = {
          'Authorization': `Bearer ${token}`,
          'x-auth-token': token
        };
        
        console.log('获取申请详情');
        
        // 获取完整申请详情
        const response = await axios.get(`${API_URL}/adoptions/applications/${application.id}`, { headers });
        
        if (response.data) {
          const detailData = response.data;
          // 不记录详细信息
          
          // 更新currentApplication
          Object.assign(currentApplication.value, detailData);
          
          // 如果没有用户详细信息，尝试获取
          if (currentApplication.value.user_id && (!currentApplication.value.email || !currentApplication.value.phone)) {
            // 不记录用户ID和请求详情
            
            // 尝试获取用户信息
            try {
              // 不记录请求URL和头信息
              
              const userResponse = await axios.get(`${API_URL}/users/${currentApplication.value.user_id}`, { headers });
              
              if (userResponse.data) {
                const userData = userResponse.data;
                // 不记录用户数据详情
                
                // 更新用户信息
                currentApplication.value.name = userData.full_name || userData.username || currentApplication.value.name;
                currentApplication.value.phone = userData.phone || currentApplication.value.phone;
                currentApplication.value.email = userData.email || currentApplication.value.email;
                currentApplication.value.address = userData.address || currentApplication.value.address;
              }
            } catch (userError) {
              // 尝试另一个API端点
              try {
                const userResponse = await axios.get(`${API_URL}/users?id=${currentApplication.value.user_id}`, { headers });
                
                if (userResponse.data && userResponse.data.length > 0) {
                  const userData = userResponse.data[0];
                  // 不记录用户数据详情
                  
                  // 更新用户信息
                  currentApplication.value.name = userData.full_name || userData.username || currentApplication.value.name;
                  currentApplication.value.phone = userData.phone || currentApplication.value.phone;
                  currentApplication.value.email = userData.email || currentApplication.value.email;
                  currentApplication.value.address = userData.address || currentApplication.value.address;
                }
              } catch (secondUserError) {
                // 尝试从本地用户列表中查找
                try {
                  const userData = store.getters['users/allUsers'].find(u => u.id === currentApplication.value.user_id);
                  
                  if (userData) {
                    // 不记录用户数据详情
                    
                    // 更新用户信息
                    currentApplication.value.name = userData.full_name || userData.username || currentApplication.value.name;
                    currentApplication.value.phone = userData.phone || currentApplication.value.phone;
                    currentApplication.value.email = userData.email || currentApplication.value.email;
                    currentApplication.value.address = userData.address || currentApplication.value.address;
                  }
                } catch (localUserError) {
                  console.error('获取用户信息失败');
                }
              }
            }
          }
          
          // 不记录更新后的申请信息
          
          // 如果缺少宠物信息，尝试获取
          if (currentApplication.value.pet_id && (!currentApplication.value.pet || !currentApplication.value.pet.name)) {
            // 不记录宠物ID和请求详情
            
            try {
              const petResponse = await axios.get(`${API_URL}/pets/${currentApplication.value.pet_id}`, { headers });
              
              if (petResponse.data) {
                const petData = petResponse.data;
                // 不记录宠物数据详情
                
                // 更新宠物信息
                currentApplication.value.pet = petData;
              }
            } catch (petError) {
              console.error('获取宠物信息失败');
            }
          }
          
          // 不记录处理后的申请详情
        }
      } catch (error) {
        console.error('获取申请详情失败');
        ElMessage.error('获取申请详情失败');
      } finally {
        loadingDetail.value = false;
      }
    };
    
    // 获取宠物图片URL
    const getPetImageUrl = (pet) => {
      if (!pet) return 'https://via.placeholder.com/300x300?text=No+Image';
      
      if (!pet.image_url) {
        return 'https://via.placeholder.com/300x300?text=No+Image';
      }

      // 处理完整URL的情况
      if (pet.image_url.startsWith('http')) {
        return pet.image_url;
      }

      // 处理相对路径
      if (pet.image_url.startsWith('/')) {
        return pet.image_url;
      } else {
        return `/${pet.image_url}`;
      }
    };
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '未知';
      
      try {
        const date = new Date(dateString);
        if (isNaN(date.getTime())) {
          console.warn('无效的日期格式:', dateString);
          return '未知';
        }
        
        const options = { 
          year: 'numeric', 
          month: 'numeric', 
          day: 'numeric',
          hour: '2-digit',
          minute: '2-digit'
        };
        return date.toLocaleDateString('zh-CN', options);
      } catch (error) {
        console.error('日期格式化错误:', error, dateString);
        return '未知';
      }
    };
    
    // 格式化性别
    const formatGender = (gender) => {
      const genderMap = {
        'male': '公',
        'female': '母',
        'unknown': '未知'
      };
      return genderMap[gender] || '未知';
    };
    
    // 格式化状态
    const formatStatus = (status) => {
      if (!status) return '未知';
      
      // 统一处理状态值，可能来自不同字段
      const normalizedStatus = typeof status === 'boolean' ? 
        (status ? 'approved' : 'pending') : 
        String(status).toLowerCase();
      
      const statusMap = {
        'pending': '待审核',
        'approved': '已通过',
        'rejected': '已拒绝',
        'true': '已通过',
        'false': '待审核',
        'cancelled': '已取消'
      };
      return statusMap[normalizedStatus] || '未知';
    };
    
    // 获取状态标签类型
    const getStatusType = (status) => {
      if (!status) return 'info';
      
      // 统一处理状态值
      const normalizedStatus = typeof status === 'boolean' ? 
        (status ? 'approved' : 'pending') : 
        String(status).toLowerCase();
        
      const typeMap = {
        'pending': 'warning',
        'approved': 'success',
        'rejected': 'danger',
        'true': 'success',
        'false': 'warning',
        'cancelled': 'info'
      };
      return typeMap[normalizedStatus] || 'info';
    };
    
    // 格式化年龄
    const formatAge = (age) => {
      if (!age) return '未知';
      return `${age} 岁`;
    };
    
    // 添加获取分类名称方法
    const getCategoryName = (categoryId) => {
      if (!categoryId) return '未知';
      const category = store.getters['categories/allCategories'].find(c => c.id === categoryId);
      return category ? category.name : '未知';
    };
    
    // 处理页面变化
    const handlePageChange = (page) => {
      currentPage.value = page;
    };
    
    // 通过申请
    const approveApplication = async (application) => {
      try {
        await ElMessageBox.confirm(`确定要通过 ${application.name} 的申请吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        await processApplication(application.id, 'approved');
      } catch (error) {
        if (error !== 'cancel') {
          console.error(error);
        }
      }
    };
    
    // 拒绝申请
    const rejectApplication = async (application) => {
      try {
        await ElMessageBox.confirm(`确定要拒绝 ${application.name} 的申请吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        await processApplication(application.id, 'rejected');
      } catch (error) {
        if (error !== 'cancel') {
          console.error(error);
        }
      }
    };
    
    // 通过申请（带备注）
    const approveApplicationWithComment = async () => {
      if (!currentApplication.value) return;
      try {
        await processApplication(currentApplication.value.id, 'approved', processForm.value.admin_comments);
        detailDialogVisible.value = false;
      } catch (error) {
        console.error(error);
      }
    };
    
    // 拒绝申请（带备注）
    const rejectApplicationWithComment = async () => {
      if (!currentApplication.value) return;
      try {
        await processApplication(currentApplication.value.id, 'rejected', processForm.value.admin_comments);
        detailDialogVisible.value = false;
      } catch (error) {
        console.error(error);
      }
    };
    
    // 处理申请
    const processApplication = async (id, status, comments = '') => {
      processing.value = true;
      try {
        const data = {
          status,
          admin_comments: comments
        };
        
        // 获取token
        const token = store.getters['auth/token'];
        
        // 设置认证头
        const headers = {
          'Authorization': `Bearer ${token}`,
          'x-auth-token': token,
          'Content-Type': 'application/json'
        };
        
        console.log('更新申请状态');
        
        const response = await axios.put(`${API_URL}/adoptions/applications/${id}`, data, { headers });
        
        // 不记录响应详情
        
        // 更新本地状态
        const index = applications.value.findIndex(app => app.id === id);
        if (index !== -1) {
          applications.value[index].status = status;
          applications.value[index].admin_comments = comments;
          
          // 如果是通过申请，同时更新宠物的领养状态
          if (status === 'approved' && applications.value[index].pet) {
            applications.value[index].pet.is_adopted = true;
          }
        }
        
        const statusText = status === 'approved' ? '通过' : '拒绝';
        ElMessage.success(`已${statusText}申请`);
        
        // 关闭对话框
        if (detailDialogVisible.value) {
          detailDialogVisible.value = false;
        }
        
        // 更新成功后立即重新加载数据列表，确保所有状态都是最新的
        await loadApplications();
        
      } catch (error) {
        console.error('处理申请失败:', error);
        const errorMessage = error.response?.data?.message || `处理申请失败(${error.message || '未知错误'})`;
        ElMessage.error(errorMessage);
      } finally {
        processing.value = false;
      }
    };
    
    // 监听搜索词和状态过滤器变化，重置页码
    watch([searchQuery, statusFilter], () => {
      currentPage.value = 1;
    });
    
    // 判断申请是否为待处理状态
    const isStatusPending = (application) => {
      if (!application) return false;
      
      // 如果有明确的status字段
      if (application.status) {
        if (typeof application.status === 'string') {
          return application.status.toLowerCase() === 'pending';
        }
        // 如果status是布尔值或数字
        return !application.status; // false或0表示待处理
      }
      
      // 如果通过宠物的is_adopted状态判断
      if (application.pet && application.pet.is_adopted !== undefined) {
        return !application.pet.is_adopted;
      }
      
      // 默认情况
      return false;
    };
    
    // 监听路由参数变化
    watch(() => route.query.status, (newStatus) => {
      if (newStatus) {
        statusFilter.value = newStatus;
      }
    }, { immediate: true });
    
    // 组件挂载时加载数据
    onMounted(() => {
      // 如果URL中有status参数，设置状态过滤器
      if (route.query.status) {
        statusFilter.value = route.query.status;
      }
      loadApplications();
    });

    const handleStatusChange = (value) => {
      // 更新路由查询参数
      if (value) {
        router.push({ query: { ...route.query, status: value } });
      } else {
        // 如果选择"全部状态"，则移除status参数
        const query = { ...route.query };
        delete query.status;
        router.push({ query });
      }
    };
    
    // 处理下拉菜单命令
    const handleCommand = (command, application) => {
      switch(command) {
        case 'view':
          viewApplication(application);
          break;
        case 'approve':
          approveApplication(application);
          break;
        case 'reject':
          rejectApplication(application);
          break;
      }
    };
    
    return {
      loading,
      applications,
      filteredApplications,
      searchQuery,
      statusFilter,
      currentPage,
      pageSize,
      totalApplications,
      detailDialogVisible,
      currentApplication,
      processForm,
      processing,
      loadError,
      getPetImageUrl,
      formatDate,
      formatGender,
      formatStatus,
      getStatusType,
      handlePageChange,
      viewApplication,
      approveApplication,
      rejectApplication,
      approveApplicationWithComment,
      rejectApplicationWithComment,
      loadApplications,
      getApplicationStats,
      isStatusPending,
      currentPet,
      currentUser,
      loadingDetail,
      formatAge,
      getCategoryName,
      handleStatusChange,
      handleCommand
    };
  }
}
</script>

<style lang="scss" scoped>
@use "sass:color";

.admin-applications {
  min-height: calc(100vh - 200px);
  padding: 40px 0;
}

.admin-actions {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  
  .left-actions {
    margin-right: 10px;
  }
  
  .right-actions {
    display: flex;
    align-items: center;
    
    .search-input {
      width: 300px;
      margin-right: 15px;
    }
    
    .status-filter {
      width: 150px;
    }
  }
}

.applications-table-card {
  margin-bottom: 30px;
}

.pet-info {
  display: flex;
  align-items: center;
  gap: 10px;
  
  .pet-thumbnail {
    width: 40px;
    height: 40px;
    border-radius: 4px;
    flex-shrink: 0;
  }
  
  .pet-name {
    font-size: 14px;
    color: #606266;
    
    &:hover {
      color: #409EFF;
      cursor: pointer;
    }
  }
  
  .image-placeholder {
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f7fa;
    color: #909399;
    border-radius: 4px;
  }
}

.no-data {
  color: #909399;
  font-size: 13px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

// 详情对话框样式
.application-detail {
  margin-bottom: 20px;
}

.detail-section {
  margin-top: 20px;
  
  h3 {
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
    margin-bottom: 15px;
    color: var(--secondary-color);
  }
}

.pet-detail {
  display: flex;
  
  .pet-image-container {
    width: 150px;
    margin-right: 20px;
    
    .pet-image {
      width: 150px;
      height: 150px;
      border-radius: 8px;
      object-fit: cover;
    }
  }
  
  .pet-info {
    flex: 1;
    
    p {
      margin: 8px 0;
    }
  }
}

.description-text,
.reason-text,
.environment-text,
.admin-comments {
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 4px;
  margin-top: 10px;
  white-space: pre-line;
}

.process-actions {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 4px;
}

.loading-container {
  min-height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30px;
}

.user-detail {
  margin-top: 15px;
}

@media (max-width: 768px) {
  .admin-actions {
    flex-direction: column;
    
    .search-input {
      width: 100%;
      margin-right: 0;
      margin-bottom: 10px;
    }
    
    .status-filter {
      width: 100%;
    }
  }
  
  .pet-detail {
    flex-direction: column;
    
    .pet-image-container {
      width: 100%;
      margin-right: 0;
      margin-bottom: 20px;
      
      .pet-image {
        width: 100%;
        height: auto;
      }
    }
  }
}

// 申请详情弹窗样式
.application-detail-dialog {
  :deep(.el-dialog__body) {
    padding: 20px;
  }
}

.detail-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

  h3 {
    margin: 0 0 15px 0;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
    color: #303133;
    font-size: 16px;
    font-weight: 600;
  }
}

.content-box {
  background-color: #f8f9fa;
  border-radius: 4px;
  padding: 15px;
  min-height: 60px;
  line-height: 1.6;
  color: #606266;
}

.pet-card {
  .pet-info-container {
    .pet-image-wrapper {
      width: 100%;
      height: 200px;
      margin-bottom: 15px;
      border-radius: 8px;
      overflow: hidden;
      
      .pet-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      .image-placeholder {
        width: 100%;
        height: 100%;
        background: #f5f7fa;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: #909399;
        
        i {
          font-size: 32px;
          margin-bottom: 8px;
        }
      }
    }
    
    .pet-details {
      .pet-name {
        font-size: 18px;
        font-weight: 600;
        margin-bottom: 10px;
        color: #303133;
      }
      
      .pet-meta {
        margin: 10px 0;
        color: #606266;
        
        span {
          margin-right: 15px;
          
          &:last-child {
            margin-right: 0;
          }
        }
      }
      
      .pet-status {
        margin: 10px 0;
        display: inline-block;
      }
      
      .view-pet-btn {
        margin-top: 10px;
        width: 100%;
      }
    }
  }
}

.action-card {
  .action-buttons {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-bottom: 0;
  }
}

// 响应式布局
@media (max-width: 768px) {
  .el-dialog {
    width: 95% !important;
  }
  
  .el-row {
    flex-direction: column-reverse;
  }
  
  .el-col {
    width: 100% !important;
  }
}

/* Operation button styles */
.action-button {
  min-width: 80px;
}

.approve-action {
  color: #67c23a;
}

.reject-action {
  color: #f56c6c;
}

/* Adding missing style if it doesn't exist in original styles */
.reject-action:hover {
  background-color: #fef0f0;
}

.approve-action:hover {
  background-color: #f0f9eb;
}
</style> 